<?php

/* GET INFO FROM THE DATABASE AND PUT IN DISPLAY TABLE */

/* Highlight ID/first field on default */
if ($_POST['Selected']=='') {
        $_POST['Selected']= mysql_field_name($result, 0) . " v";
}


/* Another call to get * from table is needed to show newly 
    added/deleted record */
$sql = "SELECT * FROM $tableName";

/* Figuring how to how the entries in the table */
for ($i=0; $_POST['Selected']!='' && $i < $fields; $i++) {
	if ( mysql_field_name($result, $i)== $_POST['Selected'] ||
		mysql_field_name($result, $i)==stristr($_POST['Selected'] , ' ', true)) {
		$sql = $sql . " ORDER BY ". mysql_field_name($result, $i);
		if (stristr($_POST['Selected'] , ' ')==" ^") {
			$sql = $sql . " DESC";
		} else if (stristr($_POST['Selected'] , ' ')==" v") {
			$sql = $sql . " ASC";
		} 
		break;
	}
}
$result = mysql_query($sql, $con);
if (!$result) {
	die("<p class=\"error-message\">Error: Unable to display record values in table.</p>");
}
$fields = mysql_num_fields($result);
echo "<div class=\"scrollableContainer\" style=\"width:" . (99 + (149*$fields)) ."px\">\n";
echo "<div class=\"scrollingArea\">\n";
echo "<table class=\"display scrollable\">\n";

/* Headers for Display Table */

echo "<thead><tr><th class=\"check-box\"><div></div></th>";
echo "<th class=\"edit-submit\"><div></div></th>";
for ($i=0; $i < $fields; $i++) {
        $name  = mysql_field_name($result, $i);
	echo "<th class=\"field\"><div><input ";
	if ( mysql_field_name($result, $i)== $_POST['Selected'] ||
	$name == stristr($_POST['Selected'] , ' ', true)) {
		echo "class='selected' value='" . $name;
		if (stristr($_POST['Selected'] , ' ')==" ^") {
			echo " v' ";
		} else {	
			echo " ^' ";
		}
	} else {
		echo "class='display-input' value='" . $name . "' ";
	}
	echo "type='submit' name='Selected' /></div></th>\n";
}
echo "</tr></thead>\n";

/* Display the data */

echo "<tbody>\n";
while ($row = mysql_fetch_assoc($result)) {
    echo "<tr>\n";

    /* For Delete Box */

    echo "<td class=\"check-box\"><div>";
    echo "<input type='checkbox' ";
    if ($_POST['DeleteSelected']=='Select All') {
	echo "checked='yes' ";
    }
    echo "name='delete_" . $row[mysql_field_name($result, 0)] . "' value='Yes' />";
    echo "</div></td>\n";

    /* For Edit Button */

    echo "<td class=\"edit-submit\"><div>";
    echo "<input type='submit' name='edit_"  .  $row[mysql_field_name($result, 0)] . "' value='Edit' />";
    echo "</div></td>";

    /* The remainder values */

    for ($i=0; $i < $fields; $i++) {
        echo "<td class=\"field\"><div>";
	echo htmlspecialchars($row[mysql_field_name($result, $i)]);
	echo "</div></td>\n";
    }
    echo "</tr>\n";
}
echo "</tbody>\n</table>\n";
echo "</div></div>\n"; /* Close divs for scrolling */
echo "<p><input type='submit' name='DeleteSelected' value='Select All' /> ".
	"<input type='submit' name='DeleteSelected' value='Delete Selected' /></p>\n";

?>
